<?php

namespace app\technician_api\controller;

use app\common\controller\Technician;
use app\common\facade\Token;
use ba\Random;
use think\facade\Db;

class Login extends Technician
{
    protected array $noNeedLogin = ['login', 'technician_login_sms', 'technician_login', 'retrieve_sms_check', 'retrieve_sms', 'update_motto'];
    protected array $noNeedPermission = ['*'];
    protected string $token = "";

    // 更新用户手机号
    public function update_motto ()
    {
        $params = $this->request->param();
        if (empty($params['mobile']))
            $this->error("手机号不能为空");
        if (empty($params['motto']))
            $this->error("密码不能为空");
        $model = new \app\technician_api\model\Technician;
        $data = $model->where(['username' => $params['mobile']])
            ->order("technician_id", 'desc')
            ->find();
        if (!$data) {
            $this->error("未查询到用户信息");
        }
        // md5($password . $this->model->salt)
        $data->motto = md5($params['motto']);
        $data->password = encrypt_password($params['motto'], $data['salt']);
        $data->save();
        $this->success("修改成功");
    }

    /**
     * 技师找回密码发送短信
     */
    public function retrieve_sms ()
    {
        $params = $this->request->param();
        if (empty($params['mobile']))
            $this->error("手机号不能为空");
        $send = sms_send($params['mobile'], 'technician_reset_password');
        if (!$send) {
            $this->error("短信发送失败");
        }
        $this->success("短信发送成功");
    }

    /**
     * 验证找回密码的验证码
     */
    public function retrieve_sms_check ()
    {
        $params = $this->request->param();
        if (empty($params['mobile']))
            $this->error("手机号不能为空");
        if (empty($params['code']))
            $this->error("验证码不能为空");

        try {
            sms_check($params['mobile'], $params['code'], 'technician_reset_password');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success("验证成功");
    }

    /**
     * 发送短信
     */
    public function technician_login_sms ()
    {
        $params = $this->request->param();
        if (empty($params['mobile']))
            $this->error("手机号不能为空");
        $send = sms_send($params['mobile'], 'technician_login');
        if (!$send) {
            $this->error("短信发送失败");
        }
        $this->success("短信发送成功");
    }

    /**
     * 手机号验证码登录
     */
    public function technician_login ()
    {
        $params = $this->request->param();
        if (empty($params['mobile']))
            $this->error("手机号不能为空");
        if (empty($params['code']))
            $this->error("验证码不能为空");
        try {
            sms_check($params['mobile'], $params['code'], 'technician_login');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $zh = Db::table("ba_technician")
            ->where([
                'username' => $params['mobile']
            ])
            ->order("technician_id", 'desc')
            ->find();
        if (!$zh) {
            $this->error('当前账号未注册，请申请入驻后重试！');
        }

        $res = $this->auth->fetchLogin($params['mobile']);
        if ($res !== true) {
            $msg = $this->auth->getError();
            $msg = $msg ?: __('Check in failed, please try again or contact the website administrator~');
            $this->error($msg);
        }
        Db::table('ba_sms')
            ->where([
                'event'  => 'technician_login',
                'mobile' => $params['mobile'],
            ])
            ->delete();
        $userinfo = $this->auth->getUserInfo();
        $userinfo['avatar'] = IMAGE_URL . $userinfo['avatar'];

        $this->success(__('Login succeeded!'), [
            'userInfo'  => $userinfo,
            'routePath' => '/technician'
        ]);
    }


    public function login ()
    {
        $params = $this->request->param();
        if (empty($params['username']) || empty($params['password'])) {
            $this->error('账号或密码错误！');
        }

        $username = $params['username'];
        $password = $params['password'];

        $technicianInfo = \app\technician_api\model\Technician::where('username', $username)->find();
        if (!$technicianInfo) {
            $this->error('当前账号未注册，请申请入驻后重试！');
        }

        if ($technicianInfo->status != 1) {
            $this->error('当前账号已被禁用，请联系管理员！');
        }


        // 检查登录态
        if ($this->auth->isLogin()) {
            $this->success('已登录请勿重复登录！', [
                'type'  => $this->auth->tel,
                'token' => $this->auth->getToken()
            ], $this->auth::LOGIN_RESPONSE_CODE);
        }
        $res = $this->auth->login($username, $password);
        if ($res !== true) {
            $msg = $this->auth->getError();
            $msg = $msg ?: __('Check in failed, please try again or contact the website administrator~');
            $this->error($msg);
        }
        $userinfo = $this->auth->getUserInfo();
        $userinfo['avatar'] = IMAGE_URL . $userinfo['avatar'];

        $this->success(__('Login succeeded!'), [
            'userInfo'  => $userinfo,
            'routePath' => '/technician'
        ]);
    }

    /**
     * 技师信息
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function TechnicianInfo (): void
    {
        $technicianInfo = \app\technician_api\model\Technician::where('technician_id', $this->auth->technician_id)->find();
        if (!$technicianInfo) {
            $this->error('当前账号未注册，请申请入驻后重试！');
        }
        $info = [
            'technician_id'      => $technicianInfo->technician_id,
            'username'           => $technicianInfo->username,
            'avatar'             => IMAGE_URL . $technicianInfo->avatar,
            'technician_name'    => $technicianInfo->technician_name,
            'sex'                => $technicianInfo->sex,
            'birthday'           => $technicianInfo->birthday,
            'tel'                => $technicianInfo->tel,
            'practice_time'      => $technicianInfo->practice_time,
            'address'            => $technicianInfo->address,
            'brief_introduction' => $technicianInfo->brief_introduction,
            'is_go_work'         => $technicianInfo->is_go_work,
            'is_travel'          => $technicianInfo->is_travel,
            'score'              => $technicianInfo->score,
            'service_order_num'  => $technicianInfo->service_order_num,
            'token'              => $this->token
        ];
        $this->success('', $info);
    }

    public function layout ()
    {
        $res = $this->auth->logout();
        if (!$res) {
            $this->error('退出失败！');
        }
        $this->success('退出成功！');
    }
}